package com.salim.leetcode.$102;

import com.salim.leetcode.$101.SymmetricTree1;
import com.salim.leetcode.util.TreeNode;
import com.salim.leetcode.util.TreeNodeUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class BinaryTreeLevelOrderTraversal {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            List<Integer> currentLevel = new ArrayList<>();
            int count = queue.size();
            boolean hasValue = false;
            while (count!=0){
                TreeNode current = queue.poll();
                if(current!=null){
                    currentLevel.add(current.val);
                    if(current.left==current.right &&current.left==null){

                    }else{
                        queue.add(current.left);
                        queue.add(current.right);
                    }
                    hasValue = true;
                }
                count--;
            }
            if(hasValue){
                result.add(currentLevel);
            }
        }
        return result;
    }

    public static void main(String[] args){
        Integer[] arr = {3,9,20,null,null,15,7};
        TreeNode root = TreeNodeUtils.generateTreeNode(arr);
        BinaryTreeLevelOrderTraversal binaryTreeLevelOrderTraversal = new BinaryTreeLevelOrderTraversal();
        log.info("[3,9,20,null,null,15,7],{}",binaryTreeLevelOrderTraversal.levelOrder(root));
        Integer[] arr2 = {1};
        root = TreeNodeUtils.generateTreeNode(arr2);
        log.info("[1],{}",binaryTreeLevelOrderTraversal.levelOrder(root));
        Integer[] arr3 = {};
        root = TreeNodeUtils.generateTreeNode(arr3);
        log.info("[],{}",binaryTreeLevelOrderTraversal.levelOrder(root));
        Integer[] arr4 = {1,2};
        root = TreeNodeUtils.generateTreeNode(arr4);
        log.info("[1,2],{}",binaryTreeLevelOrderTraversal.levelOrder(root));
    }
}
